package com.zp.self.module.工具.json转换.jsonUtil;

/**
 * JsonUtils 方法包
 */

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


import java.io.IOException;
import java.util.Map;

public class JsonUtils_gc {


    static ObjectMapper mapper = new ObjectMapper();
    static{
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    }
    private JsonUtils_gc(){}

    /**
     * Description: 对象转json
     * @param o
     * @return java.lang.String
     */
    public static String toJsonStr(Object o){
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取json字符串中 某个值
     * @param str json 字符串
     * @param key 里面的值
     * @return
     */
    public static String getJsonValue(String str,String key){
        try {
            JsonNode node = mapper.readTree(str);
            String value = node.get(key).textValue();
            return value;
        } catch (IOException e) {
        }
        return null;
    }

    public static Map<String,Object> pasertJsonMap(String content){
        try {
            return mapper.readValue(content,Map.class);

        } catch (IOException e) {
        }
        return null;
    }

    public static String getJsonValue(String str,String key1,String key2){
        try {
            JsonNode node = mapper.readTree(str);
            String value = node.get(key1).get(key2).textValue();
            return value;
        } catch (IOException e) {
        }
        return null;
    }

    public static <T>T pasertJson(String content, Class<T> valueType){
        try {
            return (T)mapper.readValue(content,valueType);
        } catch (IOException e) {
        }
        return null;
    }


    public static String writeJson(Object o){
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static <T> T parseJson(String content, TypeReference<T> typeReference) {
        try {
            return mapper.readValue(content, typeReference);
        } catch (Exception e) {
        }
        return null;
    }


    public static <T> T CollectionFromJson(String content, Class collect, Class clazz)  {
        try {
            return mapper.readValue(content, mapper.getTypeFactory().constructCollectionType(collect, clazz));
        } catch (IOException e) {
        }
        return null;
    }
}